package beavers.studio.utilities.threads;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import beavers.studio.golfberry.FileManager;
import beavers.studio.golfberry.screens.MapScreen;
import beavers.studio.utilities.Utils;
import beavers.studio.utilities.callbacks.WebDataCallback;

public class MapDownloadThread extends Thread implements WebDataCallback {
	//Thread attributes
	MapScreen 	m_MapScreen;
	byte[] 		m_BufferImage;
	
	//Thread constructor
	public MapDownloadThread(MapScreen mapScreen) {
		m_MapScreen = mapScreen;
		m_BufferImage = null;
		
		//Set flag
		MapScreen.m_Run = true;
	}
	
	public void run() {	
		System.out.println("Image Download Thread Started.");
		
		//Check existing image
		int i = m_MapScreen.getNumImages();
		
		//Download and display remaining image
		while (i<m_MapScreen.getMaximumImages()) {
			//Download image
			String m_Url = "http://localhost/GolfBerry/images/map/" + i + ".jpeg";
			System.out.println("Downloading from : " + m_Url);
			
			Utils.getWebData(m_Url, this);
			
			//Sleep until download finished
			while (m_BufferImage==null) {		
				try {
					sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			System.out.println("Image downloaded.");
			
			//Add display event to queue
			final String m_Path = "map-" + i + ".jpeg";
			UiApplication.getUiApplication().invokeAndWait(new Runnable() { 
	            public void run() { 
	            	//Save to file
	            	boolean m_Success = FileManager.inst().saveImage(m_BufferImage, m_Path);
	            	System.out.println("Success saving file : " + m_Success);
	            	
	            	//Iterate current map images number
	            	m_MapScreen.setNumImages(m_MapScreen.getNumImages()+1);
	            	
	            	//Display
	            	m_MapScreen.add(new BitmapField(Bitmap.createBitmapFromBytes(m_BufferImage, 0, m_BufferImage.length, 1)));
	            } 
	        });
			
			System.out.println("Image added.");
			
			//Reset and Iterate
			m_BufferImage = null;
			i++;
			
			System.out.println("Loop " + i + " from " + m_MapScreen.getMaximumImages() + " finished.");
		}
		
		System.out.println("Download thread finished.");
	}

	public void callback(byte[] encodedImage) {
		System.out.println("Image callback received.");
		
		//Act accordingly
		if (encodedImage!=null) m_BufferImage = encodedImage;
	}
}
